home *** CD-ROM | disk | FTP | other *** search
/ Software Vault: The Gold Collection / Software Vault - The Gold Collection (American Databankers) (1993).ISO / cdr26 / netprog.zip / NETPROG.TAR / net.s5 / tcpserv.c < prev    next >
C/C++ Source or Header  |  1989-12-17  |  2KB  |  73 lines

  1. /*
  2.  * Example of server using TCP protocol.
  3.  */
  4.  
  5. #include    "inet.h"
  6.  
  7. main(argc, argv)
  8. int    argc;
  9. char    *argv[];
  10. {
  11.     int            tfd, newtfd, clilen, childpid;
  12.     struct sockaddr_in    cli_addr, serv_addr;
  13.     struct t_bind        req;
  14.     struct t_call        *callptr;
  15.  
  16.     pname = argv[0];
  17.  
  18.     /*
  19.      * Create a TCP transport endpoint.
  20.      */
  21.  
  22.     if ( (tfd = t_open(DEV_TCP, O_RDWR, (struct t_info *) 0)) < 0)
  23.         err_dump("server: can't t_open %s", DEV_TCP);
  24.  
  25.     /*
  26.      * Bind our local address so that the client can send to us.
  27.      */
  28.  
  29.     bzero((char *) &serv_addr, sizeof(serv_addr));
  30.     serv_addr.sin_family      = AF_INET;
  31.     serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  32.     serv_addr.sin_port        = htons(SERV_TCP_PORT);
  33.  
  34.     req.addr.maxlen = sizeof(serv_addr);
  35.     req.addr.len    = sizeof(serv_addr);
  36.     req.addr.buf    = (char *) &serv_addr;
  37.     req.qlen        = 5;
  38.  
  39.     if (t_bind(tfd, &req, (struct t_bind *) 0) < 0)
  40.         err_dump("server: can't t_bind local address");
  41.  
  42.     /*
  43.      * Allocate a t_call structure for t_listen() and t_accept().
  44.      */
  45.  
  46.     if ( (callptr = (struct t_call *) t_alloc(tfd, T_CALL, T_ADDR)) == NULL)
  47.         err_dump("server: t_alloc error for T_CALL");
  48.  
  49.     for ( ; ; ) {
  50.         /*
  51.          * Wait for a connection from a client process.
  52.          * This is an example of a concurrent server.
  53.          */
  54.  
  55.         if (t_listen(tfd, callptr) < 0)
  56.             err_dump("server: t_listen error");
  57.  
  58.         if ( (newtfd = accept_call(tfd, callptr, DEV_TCP, 1)) < 0)
  59.             err_dump("server: accept_call error");
  60.  
  61.         if ( (childpid = fork()) < 0)
  62.             err_dump("server: fork error");
  63.  
  64.         else if (childpid == 0) {    /* child process */
  65.             t_close(tfd);        /* close original endpoint */
  66.             str_echo(newtfd);    /* process the request */
  67.             exit(0);
  68.         }
  69.  
  70.         close(newtfd);        /* parent process */
  71.     }
  72. }
  73.